package com.hupu.jrs.ui.forum

import android.content.Context
import android.content.Intent

import com.gzsll.hupu.data.ForumRepository
import com.gzsll.hupu.db.Forum
import com.gzsll.hupu.injector.PerActivity
import com.gzsll.hupu.otto.DelForumAttentionEvent
import com.gzsll.hupu.service.OffLineService
import com.gzsll.hupu.util.ToastUtil
import com.squareup.otto.Bus

import java.util.ArrayList

import javax.inject.Inject

import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.functions.Action1

/**
 * Created by sll on 2016/3/11.
 */
@PerActivity
class ForumListPresenter @Inject
constructor(private val mForumRepository: ForumRepository, private val mContext: Context, private val mBus: Bus) : ForumListContract.Presenter {

    private var mForumListView: ForumListContract.View? = null
    private var mSubscription: Subscription? = null

    override fun onForumListReceive(forumId: String) {
        mForumListView!!.showLoading()
        mSubscription = mForumRepository.getForumList(forumId).observeOn(AndroidSchedulers.mainThread())
                .subscribe(Action1<List<Any>> { fora ->
                    if (fora == null || fora.isEmpty()) {
                        mForumListView!!.onError()
                    } else {
                        mForumListView!!.hideLoading()
                        mForumListView!!.renderForumList(fora)
                    }
                }, Action1<Throwable> { throwable -> throwable.printStackTrace() })
    }

    override fun onForumAttentionDelClick(forum: Forum) {
        mForumRepository.removeForum(forum.getFid())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(Action1<Boolean> { aBoolean ->
            if (aBoolean != null && aBoolean) {
                ToastUtil.showToast("取消关注成功")
                mBus.post(DelForumAttentionEvent(forum.getFid()))
                mForumListView!!.removeForum(forum)
            }
        }, Action1<Throwable> { ToastUtil.showToast("取消关注失败，请重试") })
    }

    override fun onForumOfflineClick(forum: Forum) {
        val intent = Intent(mContext, OffLineService::class.java)
        val forums = ArrayList<Forum>()
        forums.add(forum)
        intent.putExtra(OffLineService.EXTRA_FORUMS, forums)
        intent.action = OffLineService.START_DOWNLOAD
        mContext.startService(intent)
    }

    override fun onForumClick(forum: Forum) {
        mForumListView!!.showThreadUi(forum.getFid())
    }

    fun attachView(view: ForumListContract.View) {
        mForumListView = view
    }

    fun detachView() {
        if (mSubscription != null && !mSubscription!!.isUnsubscribed) {
            mSubscription!!.unsubscribe()
        }
        mForumListView = null
    }
}
